<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('易达电表数据统计')" />

</head>
<body class="gray-bg">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="formId">
                    <div class="select-list">
                        <ul>
                            <li>
                                <label>开始时间：</label>
                                <input type="text" class="time-input" id="startTime" placeholder="开始时间" style="width: 180px;" data-type="date" data-format="yyyy-MM-dd HH:mm"/>
                            </li>
                            <li>
                                <label>结束时间：</label>
                                <input type="text" class="time-input" id="endTime" placeholder="结束时间" style="width: 180px;" data-type="date" data-format="yyyy-MM-dd HH:mm"/>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="searchStatistics()"><i class="fa fa-search"></i>&nbsp;查询</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 功率曲面图 -->
        <div class="row">
            <div class="col-sm-12 select-table">
                <div class="ibox float-e-margins">
                    
                    <div class="ibox-content">
                        <div id="powerChart" style="height: 400px;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: echarts-js" />
    
    <style>
        /* 统一调整各区域间距 */
        .search-collapse {
            margin-bottom: 2px !important;
        }
        
        .search-collapse .select-list {
            margin-bottom: 0 !important;
            padding-bottom: 3px !important;
        }
        
        /* 统一图表和表格区域的间距 */
        .select-table {
            margin-bottom: 2px !important;
            padding-top: 15px !important;
        }
        
        .select-table .ibox {
            margin-bottom: 0 !important;
        }
        
        /* 调整容器高度 */
        .container-div .row {
            height: auto !important;
        }
    </style>

    <script th:inline="javascript">
        var ctx = [[@{/}]];
        var prefix = ctx + "system/ydmeterdata";
        var powerChart = null;

        // 在$(function() {})中，确保设置日期后立即调用searchPowerData
        $(function() {
            // 默认设置为最近两小时
            setLastTwoHours();
        
            // 确保ECharts已加载
            if (typeof echarts !== 'undefined') {
                initPowerChart();
                searchPowerData(); // 页面加载完成后立即执行一次查询
                
                // 响应窗口大小变化，重绘图表
                $(window).off('resize.powerChart');
                $(window).on('resize.powerChart', function() {
                    if (powerChart && !powerChart.isDisposed()) {
                        powerChart.resize();
                    }
                });
            } else {
                console.error("ECharts library not loaded.");
                $.modal.alertError("图表库加载失败，请刷新页面重试");
            }
        });

        // 设置最近两小时的时间范围
        function setLastTwoHours() {
            var now = new Date();
            var twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
            
            // 格式化当前时间
            var currentYear = now.getFullYear();
            var currentMonth = ("0" + (now.getMonth() + 1)).slice(-2);
            var currentDay = ("0" + now.getDate()).slice(-2);
            var currentHour = ("0" + now.getHours()).slice(-2);
            var currentMinute = ("0" + now.getMinutes()).slice(-2);
            var currentTime = currentYear + "-" + currentMonth + "-" + currentDay + " " + currentHour + ":" + currentMinute;
            
            // 格式化两小时前的时间
            var twoHoursYear = twoHoursAgo.getFullYear();
            var twoHoursMonth = ("0" + (twoHoursAgo.getMonth() + 1)).slice(-2);
            var twoHoursDay = ("0" + twoHoursAgo.getDate()).slice(-2);
            var twoHoursHour = ("0" + twoHoursAgo.getHours()).slice(-2);
            var twoHoursMinute = ("0" + twoHoursAgo.getMinutes()).slice(-2);
            var twoHoursTime = twoHoursYear + "-" + twoHoursMonth + "-" + twoHoursDay + " " + twoHoursHour + ":" + twoHoursMinute;
            
            $('#startTime').val(twoHoursTime);
            $('#endTime').val(currentTime);
        }

        // 重置表单 - 修改为显示最近两小时
        function resetForm() {
            setLastTwoHours(); // 使用已有的函数设置带时分的日期
            searchPowerData();
        }

        // 获取当前日期
        function getNowFormatDate() {
            var date = new Date();
            var year = date.getFullYear();
            var month = ("0" + (date.getMonth() + 1)).slice(-2);
            var day = ("0" + date.getDate()).slice(-2);
            return year + "-" + month + "-" + day;
        }

        // 初始化功率曲面图
        function initPowerChart() {
            powerChart = echarts.init(document.getElementById('powerChart'));
            var option = {
                title: {
                    text: '功率曲线图',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        var time = new Date(params[0].value[0]).toLocaleString();
                        var power = params[0].value[1];
                        return '时间: ' + time + '<br/>功率: ' + power + ' kW';
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'time',
                    name: '时间',
                    nameLocation: 'middle',
                    nameGap: 30,
                    boundaryGap: false,
                    axisLine: {
                        show: true
                    },
                    axisTick: {
                        show: true
                    },
                    splitLine: {
                        show: true
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '有功功率(kW)',
                    nameLocation: 'middle',
                    nameGap: 50,
                    axisLine: {
                        show: true
                    },
                    axisTick: {
                        show: true
                    },
                    splitLine: {
                        show: true
                    }
                },
                series: [
                    {
                        name: '功率数据',
                        type: 'line',
                        data: [],
                        areaStyle: {}, // 简化面积样式，与powerStatistics保持一致
                        itemStyle: {
                            color: '#1ab394'
                        },
                        lineStyle: {
                            width: 2
                        },
                        smooth: true // 平滑曲线
                    }
                ]
            };
            powerChart.setOption(option);
        }
        // 搜索功率数据
        function searchPowerData() {
            var startTime = $('#startTime').val();
            var endTime = $('#endTime').val();
        
            if (!startTime || !endTime) {
                $.modal.alertWarning("请选择开始时间和结束时间");
                return;
            }
        
            // 检查时间格式，如果只有日期没有时间，则添加默认时间
            if (startTime.length <= 10) {
                startTime = startTime + " 00:00";
            }
            
            if (endTime.length <= 10) {
                endTime = endTime + " 23:59";
            }
            
            // 为后端接口添加秒，保持兼容性
            var startDate = startTime + ":00";
            var endDate = endTime + ":59";
        
            $.ajax({
                type: "POST",
                url: prefix + "/list",
                data: {
                    startDate: startDate,
                    endDate: endDate,
                    pageNum: 1,
                    pageSize: 10000
                },
                success: function(result) {
                    if (result.code === 0) {
                        updatePowerChart(result.rows);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                }
            });
        }

        // 更新功率图表
        function updatePowerChart(data) {
            if (!powerChart || powerChart.isDisposed()) {
                initPowerChart();
            }
            
            var chartData = [];
            
            if (data && data.length > 0) {
                // 按时间排序数据
                data.sort(function(a, b) {
                    return new Date(a.collectTime) - new Date(b.collectTime);
                });
                
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var time = new Date(item.collectTime).getTime();
                    var power = item.activePower ? parseFloat(item.activePower) : 0;
                    chartData.push([time, power]);
                }
            }
            
            // 计算时间范围
            var startTime = new Date($('#startTime').val());
            var endTime = new Date($('#endTime').val());
            var timeDiff = endTime.getTime() - startTime.getTime();
            var daysDiff = timeDiff / (1000 * 3600 * 24);
            
            // 生成X轴数据
            var xAxisLabels = [];
            var xAxisData = [];
            
            if (daysDiff <= 1) {
                // 一天内查询：生成24个整点时间标签，但显示所有原始数据
                for (var hour = 0; hour < 24; hour++) {
                    var timeLabel = hour.toString().padStart(2, '0') + ':00';
                    xAxisLabels.push(timeLabel);
                }
                
                // 将原始数据映射到对应的时间点
                var dataMap = {};
                for (var i = 0; i < chartData.length; i++) {
                    var dataTime = new Date(chartData[i][0]);
                    var timeKey = dataTime.getHours().toString().padStart(2, '0') + ':' + 
                                 dataTime.getMinutes().toString().padStart(2, '0');
                    if (!dataMap[timeKey]) {
                        dataMap[timeKey] = [];
                    }
                    dataMap[timeKey].push({time: timeKey, value: chartData[i][1]});
                }
                
                // 转换为ECharts可用的数据格式
                xAxisData = [];
                for (var key in dataMap) {
                    for (var j = 0; j < dataMap[key].length; j++) {
                        xAxisData.push([key, dataMap[key][j].value]);
                    }
                }
            } else {
                // 多天查询：使用原始数据，保持时间和数值的完整格式
                for (var i = 0; i < chartData.length; i++) {
                    var date = new Date(chartData[i][0]);
                    var timeLabel = (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
                                   date.getHours().toString().padStart(2, '0') + ':' + 
                                   date.getMinutes().toString().padStart(2, '0');
                    xAxisLabels.push(timeLabel);
                    xAxisData.push([chartData[i][0], chartData[i][1]]); // 保持[时间, 数值]格式
                }
            }
            
            var option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        var param = params[0];
                        if (daysDiff <= 1) {
                            // 一天内查询：显示时间和功率
                            var date = new Date(param.data[0]);
                            var timeStr = date.getHours().toString().padStart(2, '0') + ':' + 
                                         date.getMinutes().toString().padStart(2, '0');
                            return '时间: ' + timeStr + '<br/>功率: ' + param.data[1] + ' kW';
                        } else {
                            // 多天查询：显示完整日期时间和功率
                            var date = new Date(param.data[0]);
                            var timeStr = (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
                                         date.getHours().toString().padStart(2, '0') + ':' + 
                                         date.getMinutes().toString().padStart(2, '0');
                            return '时间: ' + timeStr + '<br/>功率: ' + param.data[1] + ' kW';
                        }
                    }
                },
                xAxis: {
                    type: 'time',
                    name: '时间',
                    nameLocation: 'middle',
                    nameGap: 30,
                    boundaryGap: false,
                    splitNumber: daysDiff <= 1 ? 24 : undefined,
                    axisLine: {
                        show: true
                    },
                    axisTick: {
                        show: true
                    },
                    splitLine: {
                        show: true
                    },
                    axisLabel: {
                        interval: daysDiff <= 1 ? 0 : 'auto',
                        formatter: function(value) {
                            var date = new Date(value);
                            if (daysDiff <= 1) {
                                return date.getHours().toString().padStart(2, '0') + ':' + 
                                       date.getMinutes().toString().padStart(2, '0');
                            } else {
                                return (date.getMonth() + 1) + '-' + date.getDate() + ' ' +
                                       date.getHours().toString().padStart(2, '0') + ':' + 
                                       date.getMinutes().toString().padStart(2, '0');
                            }
                        }
                    }
                },
                series: [{
                    name: '功率数据',
                    type: 'line',
                    data: chartData,
                    areaStyle: {},
                    itemStyle: {
                        color: '#1ab394'
                    },
                    lineStyle: {
                        width: 2
                    },
                    smooth: true
                }]
            };
            
            powerChart.setOption(option);
            
            // 强制执行一次重绘
            setTimeout(function() {
                if (powerChart && !powerChart.isDisposed()) {
                    powerChart.resize();
                }
            }, 200);
        }

        // 重置表单
        // 删除这个重复的resetForm函数
        // function resetForm() {
        //     var today = getNowFormatDate();
        //     $('#startTime').val(today);
        //     $('#endTime').val(today);
        //     searchPowerData();
        // }
        
        // 搜索统计数据（兼容原有调用）
        function searchStatistics() {
            searchPowerData();
        }
    </script>
</body>
</html>